package com.zhengb.nettydemos.utils;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhengbo
 * 序列化工具 使用Protostuff
 */
public class SerializeUtil {

    private static Logger logger = LoggerFactory.getLogger(SerializeUtil.class);

    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    private static <T> Schema<T> getSchema(Class<T> clazz) {
        @SuppressWarnings("unchecked")
        Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
        if (schema == null) {
            schema = RuntimeSchema.getSchema(clazz);
            if (schema != null) {
                cachedSchema.put(clazz, schema);
            }
        }
        return schema;
    }

    private static <T> byte[] serializeInternal(final T source, final Schema<T> schema, final LinkedBuffer linkedBuffer) {
        return ProtostuffIOUtil.toByteArray(source, schema, linkedBuffer);
    }

    private static <T> T deserializeInternal(final byte[] bytes, final T result, final Schema<T> schema) {
        ProtostuffIOUtil.mergeFrom(bytes, result, schema);
        return result;
    }

    public static <T> byte[] serialize(T source) {
        if (Objects.isNull(source)) {
            return null;
        }
        final LinkedBuffer linkedBuffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        Class<T> sourceClass = (Class<T>) source.getClass();
        final Schema<T> schema = getSchema(sourceClass);
        try {
            return serializeInternal(source, schema, linkedBuffer);
        } catch (Exception e) {
            logger.error("protostuff serialize error:{}", e);
            return null;
        } finally {
            linkedBuffer.clear();
        }
    }

    public static <T> T deserialize(byte[] data, Class<T> classz) {
        if (data.length <= 0 || Objects.isNull(classz)) {
            return null;
        }
        try {
            Schema<T> schema = getSchema(classz);
            return deserializeInternal(data, schema.newMessage(), schema);
        } catch (Exception e) {
            logger.error("protostuff deserialize error:{}", e);
            return null;
        }
    }
}
